package Thread;

import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * 对FockJoinPool进行学习（分支合并框架）
 */
public class FockJoinPoolExample {

    private static int threashold = 100;

    public static void main(String[] args) {
        final ForkJoinPool forkJoinPool = new ForkJoinPool();
        long startTime = System.currentTimeMillis();
        int sum = getSum();
        long endTime = System.currentTimeMillis();
        System.out.println("循环遍历结果：" + sum);
        System.out.println("使用时间："+(endTime - startTime));
        System.out.println("ForkJoin结果:"+extracted(forkJoinPool));
        long endTime1 = System.currentTimeMillis();
        System.out.println("使用时间："+(endTime1 - endTime1));

    }

    private static long extracted(ForkJoinPool forkJoinPool) {
        ForkJoinTask<Integer> result = forkJoinPool.submit(new MyRecursiveTask(0, 112360000));
        try {
            return result.get();
        } catch (InterruptedException | ExecutionException ex) {
            ex.printStackTrace();
        }
        return 0L;
    }

    private static int getSum() {
        int sum = 0;
        for (int i = 0; i <= 112360000; i++) {
            sum += i;
        }
        return sum;
    }

    private static class MyRecursiveTask extends RecursiveTask<Integer> {

        private final int start;

        private final int end;


        private MyRecursiveTask(int start, int end) {
            this.start = start;
            this.end = end;
        }


        @Override
        protected Integer compute() {
            if (end - start <= threashold) {
                return IntStream.rangeClosed(start, end).sum();
            } else {
                int mid = (start + end) / 2;
                MyRecursiveTask left = new MyRecursiveTask(start, mid);
                MyRecursiveTask right = new MyRecursiveTask(mid+1, end);
                left.fork();
                right.fork();
                return left.join() + right.join();
            }

        }
    }
}
